<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语音识别</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: orange;
        }
        .words {
            width: 50vw;
            min-height: 500px;
            background-color: #fff;
            margin: 50px auto;
        }
    </style>
</head>
<body>
    <div class="words" contenteditable>
    </div>

    <script>
        // JS语音识别 webkitSpeechRecognition---web语音识别API
        window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        
        const recognition = new SpeechRecognition()
        // interimResults默认false 设置为true，语音识别的结果返回
        recognition.interimResults = true
        // 识别语言
        recognition.lang = 'zh-Hans'

        let p = document.createElement('p')
        const words = document.querySelector('.words')
        words.appendChild(p)
        // 获取语音输入的结果
        recognition.addEventListener('result',e=>{
            // console.log(e.results);
            let reanscript = Array.from(e.results)
                .map(result => result[0])
                .map(result => result.reanscript)
                .join('')
            
            let filter = reanscript
                .replace('逗号',',')
                .replace('冒号',':')
                .replace('句号','。')
                .replace('问号','？')
                .replace('感叹号','！')
            p.textContent = filter

            // console.log(reanscript);
            if(e.results[0].isFinal){
                p = document.createElement('p')
                words.appendChild(p)
            }

            if(reanscript.includes('clear')) {
                words.innerHTML = ''
            }
        })
        // 当语音识别关闭的时候 再次开启
        recognition.addEventListener( 'end' , recognition.start)
        // 开启语音识别
        recognition.start()


    </script>
</body>
</html>